<template>
  <view class="container">
    <view class="header">
      <text class="title">区域管理</text>
      <view class="actions">
        <view class="btn primary" @tap="addTopLevel">
          <uni-icons type="plusempty" size="14" color="#ffffff"></uni-icons>
          <text class="btn-text">添加顶级区域</text>
        </view>
      </view>
    </view>

    <view class="cards-container">
      <view
        v-for="row in flatAreas"
        :key="row.id"
        class="area-card"
      >
        <view class="card-header">
          <view class="area-info">
            <view class="name-section">
              <view class="level-indicator" :style="{ marginLeft: (row._level * 32) + 'rpx' }">
                <view v-if="row.children && row.children.length" class="expander" @tap="toggleExpand(row.id)">
                  <uni-icons :type="isExpanded(row.id) ? 'arrowdown' : 'arrowright'" size="14" color="#52C41A"></uni-icons>
                </view>
                <view v-else class="expander-placeholder"></view>
                <text class="area-name">{{ row.name }}</text>
              </view>
              <text class="area-code">{{ row.code }}</text>
            </view>
            <view class="parent-section">
              <text class="parent-label">上级区域：</text>
              <text class="parent-name">{{ row.parentName || '无' }}</text>
            </view>
          </view>
          <view class="status-section">
            <switch :checked="row.status" @change="onToggleStatus(row, $event)"></switch>
            <text class="status-text">{{ row.status ? '启用' : '禁用' }}</text>
          </view>
        </view>
        
        <view class="card-details">
          <view class="detail-item">
            <text class="detail-label">级别：</text>
            <text class="detail-value">{{ row.level }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">排序：</text>
            <text class="detail-value">{{ row.order }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">创建时间：</text>
            <text class="detail-value">{{ row.createdAt }}</text>
          </view>
        </view>
        
        <view class="card-actions">
          <view class="action-btn add" @tap="addChild(row)">
            <uni-icons type="plusempty" size="12" color="#1AAD19"></uni-icons>
            <text>添加下级</text>
          </view>
          <view class="action-btn edit" @tap="editArea(row)">
            <uni-icons type="compose" size="12" color="#1890FF"></uni-icons>
            <text>编辑</text>
          </view>
          <view class="action-btn delete" @tap="deleteArea(row)">
            <uni-icons type="trash" size="12" color="#F5222D"></uni-icons>
            <text>删除</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      expandedIds: [],
      areas: [
        {
          id: 1, name: '北京市', code: '110000', level: '省/市', parentName: '', order: 1, status: true, createdAt: '2024-01-01 10:00:00',
          children: [
            { id: 11, name: '朝阳区', code: '110105', level: '区/县', parentName: '北京市', order: 1, status: true, createdAt: '2024-01-01 10:00:00', children: [] },
            { id: 12, name: '海淀区', code: '110108', level: '区/县', parentName: '北京市', order: 2, status: true, createdAt: '2024-01-01 10:00:00', children: [] },
          ]
        },
        {
          id: 2, name: '上海市', code: '310000', level: '省/市', parentName: '', order: 2, status: true, createdAt: '2024-01-01 10:00:00',
          children: [
            { id: 21, name: '浦东新区', code: '310115', level: '区/县', parentName: '上海市', order: 1, status: true, createdAt: '2024-01-01 10:00:00', children: [] }
          ]
        },
        {
          id: 3, name: '广东省', code: '440000', level: '省/市', parentName: '', order: 3, status: true, createdAt: '2024-01-01 10:00:00',
          children: [
            { id: 31, name: '广州市', code: '440100', level: '地级市', parentName: '广东省', order: 1, status: true, createdAt: '2024-01-01 10:00:00',
              children: [
                { id: 311, name: '天河区', code: '440106', level: '区/县', parentName: '广州市', order: 1, status: true, createdAt: '2024-01-01 10:00:00', children: [] }
              ]
            }
          ]
        }
      ]
    }
  },
  computed: {
    flatAreas() {
      // 扁平化树，仅展开 expandedIds 的子节点
      const result = [];
      const walk = (nodes, level = 0) => {
        nodes.forEach(node => {
          result.push({ ...node, _level: level });
          if (node.children && node.children.length && this.isExpanded(node.id)) {
            walk(node.children, level + 1);
          }
        });
      };
      walk(this.areas, 0);
      return result;
    }
  },
  methods: {
    isExpanded(id) {
      return this.expandedIds.includes(id);
    },
    toggleExpand(id) {
      const idx = this.expandedIds.indexOf(id);
      if (idx !== -1) this.expandedIds.splice(idx, 1);
      else this.expandedIds.push(id);
      // 触发更新
      this.expandedIds = [...this.expandedIds];
    },
    onToggleStatus(row, e) {
      const checked = e.detail ? e.detail.value : e.target?.value;
      row.status = !!checked;
      uni.showToast({ title: checked ? '启用' : '禁用', icon: 'none' });
    },
    addTopLevel() {
      uni.showModal({
        title: '添加顶级区域',
        editable: true,
        placeholderText: '请输入区域名称',
        success: (res) => {
          if (res.confirm && res.content) {
            const id = Date.now();
            this.areas.push({
              id, name: res.content, code: String(id).slice(-6), level: '省/市', parentName: '', order: this.areas.length + 1,
              status: true, createdAt: new Date().toISOString().slice(0,19).replace('T',' '), children: []
            });
          }
        }
      });
    },
    addChild(parent) {
      uni.showModal({
        title: `为 ${parent.name} 添加下级`,
        editable: true,
        placeholderText: '请输入下级区域名称',
        success: (res) => {
          if (res.confirm && res.content) {
            const id = Date.now();
            if (!parent.children) parent.children = [];
            parent.children.push({
              id, name: res.content, code: String(id).slice(-6),
              level: this.nextLevel(parent.level),
              parentName: parent.name, order: (parent.children.length || 0) + 1,
              status: true, createdAt: new Date().toISOString().slice(0,19).replace('T',' '), children: []
            });
            if (!this.isExpanded(parent.id)) this.expandedIds.push(parent.id);
            this.expandedIds = [...this.expandedIds];
          }
        }
      });
    },
    editArea(row) {
      uni.showModal({
        title: `编辑 ${row.name}`,
        editable: true,
        placeholderText: '请输入新的区域名称',
        success: (res) => {
          if (res.confirm && res.content) {
            row.name = res.content;
            uni.showToast({ title: '已更新', icon: 'none' });
          }
        }
      });
    },
    deleteArea(row) {
      uni.showModal({
        title: '确认删除',
        content: `是否删除 ${row.name}？`,
        success: (res) => {
          if (res.confirm) {
            this.removeNodeById(row.id);
            uni.showToast({ title: '已删除', icon: 'none' });
          }
        }
      });
    },
    removeNodeById(id) {
      const removeFrom = (list) => {
        const idx = list.findIndex(i => i.id === id);
        if (idx !== -1) {
          list.splice(idx, 1);
          return true;
        }
        for (const item of list) {
          if (item.children && item.children.length) {
            const ok = removeFrom(item.children);
            if (ok) return true;
          }
        }
        return false;
      };
      removeFrom(this.areas);
    },
    nextLevel(level) {
      const order = ['省/市', '地级市', '区/县'];
      const i = order.indexOf(level);
      return order[i + 1] || '区/县';
    }
  }
}
</script>

<style scoped>
.container {
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  padding: 20rpx;
  box-sizing: border-box;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24rpx;
  padding: 24rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 16rpx;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
}

.title {
  font-size: 28rpx;
  font-weight: 600;
  color: white;
  text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
}

.actions {
  display: flex;
  gap: 8px;
}

.btn {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 12rpx 18rpx;
  border-radius: 10rpx;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
}

.btn.primary {
  background: rgba(255, 255, 255, 0.2);
  backdrop-filter: blur(10rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.3);
}

.btn:active {
  transform: scale(0.95);
  box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.2);
}

.btn.primary .btn-text {
  color: #fff;
  font-size: 20rpx;
  font-weight: 500;
}

.cards-container {
  display: flex;
  flex-direction: column;
  gap: 18rpx;
}

.area-card {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 14rpx;
  padding: 18rpx;
  box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.08);
  border: 1rpx solid #e8e8e8;
  transition: all 0.3s ease;
}

.area-card:active {
  transform: translateY(-2rpx);
  box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 18rpx;
}

.area-info {
  flex: 1;
}

.name-section {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}

.level-indicator {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.expander {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 10rpx;
  background: linear-gradient(135deg, #52c41a 0%, #73d13d 100%);
  box-shadow: 0 4rpx 12rpx rgba(82, 196, 26, 0.3);
  transition: all 0.3s ease;
}

.expander:active {
  transform: scale(0.9);
}

.expander-placeholder {
  width: 40rpx;
  height: 40rpx;
}

.area-name {
  font-size: 22rpx;
  font-weight: 600;
  color: #2c3e50;
}

.area-code {
  font-size: 18rpx;
  color: #666;
  background: #f0f2f5;
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  margin-left: 8rpx;
}

.parent-section {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.parent-label {
  font-size: 20rpx;
  color: #999;
}

.parent-name {
  font-size: 20rpx;
  color: #666;
  font-weight: 500;
}

.status-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
}

.status-text {
  font-size: 18rpx;
  color: #666;
}

.card-details {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 18rpx;
  margin-bottom: 18rpx;
  padding: 18rpx;
  background: #f8f9fa;
  border-radius: 10rpx;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 6rpx;
}

.detail-label {
  font-size: 18rpx;
  color: #999;
}

.detail-value {
  font-size: 20rpx;
  color: #666;
  font-weight: 500;
}

.card-actions {
  display: flex;
  gap: 16rpx;
  justify-content: flex-end;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 6rpx;
  padding: 12rpx 18rpx;
  border-radius: 10rpx;
  font-size: 20rpx;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.action-btn:active {
  transform: scale(0.95);
  box-shadow: 0 1rpx 4rpx rgba(0, 0, 0, 0.2);
}

.action-btn.add {
  background: linear-gradient(135deg, #f6ffed 0%, #d9f7be 100%);
  color: #1AAD19;
  border: 1rpx solid #b7eb8f;
}

.action-btn.edit {
  background: linear-gradient(135deg, #f0f8ff 0%, #d6e4ff 100%);
  color: #1890FF;
  border: 1rpx solid #91d5ff;
}

.action-btn.delete {
  background: linear-gradient(135deg, #fff2f0 0%, #ffccc7 100%);
  color: #F5222D;
  border: 1rpx solid #ffa39e;
}
</style>